package helloClientController

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	ClientUtils "goGrpc/allClient/Utils"
	"goGrpc/allClient/helloClient/Model"
	pb "goGrpc/proto/protoGo"
	"google.golang.org/grpc"
	"log"
	"net/http"
)

func initGrpc() (*grpc.ClientConn, error) {
	conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
	return conn, err
}

// @Summary helloGrpcClient测试Post
// @Description helloGrpcClient测试
// @Tags 测试类
// @Produce json
// @Param helloModel body HelloModel.Hello true "helloModel"
// @Success 200 {object} ClientUtils.Res {"code":200,"data":null,"msg":""}
// @Failure 400 {object} ClientUtils.Res {"code":400,"data":null,"msg":""}
// @Router /api/v1/helloTest [post]
func TestClient(c *gin.Context) {
	// Set up a connection to the server.
	log.Printf("Test方法 \n")

	conn, err := initGrpc()
	if err != nil {
		log.Fatalf("服务端链接失败: %v", err)
	}
	log.Printf("hello服务端链接成功 \n")
	client := pb.NewHelloClient(conn)
	var input HelloModel.Hello
	if err := c.ShouldBindJSON(&input); err != nil {
		ClientUtils.ReturnMsg(c, 402, nil, err.Error())
		return
	}
	log.Printf("接口入参: %v \n", input)
	name := input.Name
	// Contact the server and print out its response.
	data, _ := json.Marshal(input)
	log.Printf("接口入参json： %v \n", string(data))
	req := &pb.HelloRequest{Name: name, AllParmas: string(data)}
	res, err := client.SayHello(c, req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		ClientUtils.ReturnMsg(c, 400, nil, err.Error())
		return
	} else {
		ClientUtils.ReturnMsg(c, 200, res.Message, res.Message)
	}

}
